package nc.pu.pub.rest;

import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.comn.NetStreamContext;
import nc.bs.framework.server.ISecurityTokenCallback;
import uap.ws.rest.resource.AbstractUAPRestResource;

import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public abstract class  AbstractReceiveOrderResource extends AbstractUAPRestResource {
    static final Logger logger = Logger.getLogger(AbstractReceiveOrderResource.class.getName());

    public AbstractReceiveOrderResource() {
        InvocationInfoProxy.getInstance().setUserDataSource("scrx");
        InvocationInfoProxy.getInstance().setGroupId("0001A210000000000Z1C");
        ISecurityTokenCallback tc = NCLocator.getInstance().lookup(
                ISecurityTokenCallback.class);
        byte[] token = tc.token("__system".getBytes(), "annoymous".getBytes());// 匿名者登录
        InvocationInfoProxy.getInstance().setUserId("NC_USER0000000000000");
        InvocationInfoProxy.getInstance().setGroupId(InvocationInfoProxy.getInstance().getGroupId());
        InvocationInfoProxy.getInstance().setUserDataSource(InvocationInfoProxy.getInstance().getUserDataSource());
        NetStreamContext.setToken(token);
        logger.setLevel(Level.INFO);
        Handler[] parentHandlers = logger.getParent().getHandlers();
        for (Handler handler : parentHandlers) {
             if(handler instanceof ConsoleHandler){
                 logger.getParent().removeHandler(handler);
             }
        }
        initLog();
    }
    private static FileHandler fileHandler;
    public static FileHandler initLog() {
        if (fileHandler == null) {
            try {
                fileHandler = new FileHandler("nclogs\\dibang.log");
                fileHandler.setEncoding("GBK");
                Formatter formatter = new SimpleFormatter();
                fileHandler.setFormatter(formatter);
                logger.addHandler(fileHandler);
            } catch (IOException e) {
                // 更好的处理方式是记录错误并向上抛出合适的异常
                e.printStackTrace();
            }
        }
        return fileHandler;
    }

    @Override
    public String getModule() {
        return "pu";
    }

    @Override
    public Logger getLogger() {
        return logger;
    }
}
